<template>
  <div class="login-box">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="60px"
      class="demo-ruleForm"
    >
      <h2>后台管理系统</h2>
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          class="loginBtn"
          @click="submitForm(ruleFormRef)"
          >登录</el-button
        >
        <el-button class="loginBtn" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from "vue";
import { LoginData } from "../type/login";
import type { FormInstance } from "element-plus";
import { login } from "../request/api";
import { useRouter } from "vue-router";

export default defineComponent({
  setup() {
    // 路由器
    const router = useRouter(); // 相当于$router

    // 这里定义一个类，用来实例一个对象
    const data = reactive(new LoginData());
    // 校验规则
    const rules = {
      username: [
        { required: true, message: "请输入用户名！", trigger: "blur" },
        { min: 3, max: 10, message: "账号长度在3-10之间", trigger: "blur" },
      ],
      password: [
        { required: true, message: "请输入密码！", trigger: "blur" },
        { min: 3, max: 10, message: "账号长度在3-10之间", trigger: "blur" },
      ],
    };

    // 登录
    const ruleFormRef = ref<FormInstance>();
    const submitForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      // 对表单内容进行验证
      formEl.validate((valid) => {
        if (valid) {
        //   console.log("submit!");
          login(data.ruleForm).then((res) => {
            // console.log("request success!");
            // console.log(res);
            // 登录成功将token保存并跳转到首页

            localStorage.setItem("token", res.data.token);
            // console.log(localStorage.getItem("token"));
            // 跳转到首页
            router.push("/");
          });
        } else {
          console.log("error submit!");
          return false;
        }
      });
    };

    // 重置
    const resetForm = () => {
      data.ruleForm.username = "";
      data.ruleForm.password = "";
    };

    return { ...toRefs(data), rules, ruleFormRef, submitForm, resetForm };
  },
});
</script>

<style scoped lang="scss">
.login-box {
  width: 100%;
  height: 100%;
  background: url("../assets/bg.jpg");
  padding: 1px;
  text-align: center;
  .demo-ruleForm {
    width: 500px;
    margin: 200px auto;
    background-color: rgb(255, 255, 255);
    padding: 40px;
    border-radius: 20px;
  }
  .loginBtn {
    width: 48%;
  }
  h2 {
    margin-bottom: 10px;
  }
}
</style>
